﻿using Autofac;
using Autofac.Core;
using AutoFacLearn.Demo.Interface;
using Microsoft.Extensions.DependencyModel;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;


namespace AutoFacLearn.注册Demo
{
    public class 扫描程序集注册
    {
        private static IContainer Container { get; set; }
        public void Demo(params Parameter[] parameters)
        {
            var builder = new ContainerBuilder();
            var baseType = typeof(IBaseAppServices);

            ///扫描所有的程序集
            List<CompilationLibrary> compilationLibrary = DependencyContext
                    .Default
                    .CompileLibraries
                    .Where(x => !x.Serviceable && x.Type != "package").ToList();

            foreach (var _compilation in compilationLibrary)
            {
                var list = AssemblyLoadContext.Default
                    .LoadFromAssemblyName(new AssemblyName(_compilation.Name));

                builder.RegisterAssemblyTypes(list)
                      .Where(t => baseType.IsAssignableFrom(t) && t.Name.EndsWith("AppServices") && !t.IsAbstract)
                      .AsImplementedInterfaces()
                      .PropertiesAutowired();
            }

            Container = builder.Build();
            using (var scope = Container.BeginLifetimeScope())
            {
                var component = scope.Resolve<IUserAppServices>();
                component.HH();
            }




        }
    }
}
